package com.web.controller.api;

import com.web.config.KftPayCommConfig;
import com.web.config.KppAppPayConfiguration;
import com.web.dao.*;
import com.web.entity.*;
import com.web.kftsdk.api.KftPayConfigStorage;
import com.web.kftsdk.api.KftPayService;
import com.web.kftsdk.entity.NotifyRes;
import com.web.manager.KftCoreManager;
import com.web.manager.jpush.SendJPushMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * Created by Welcome Chen on 2018-08-08.
 *
 * 快付通平台的异步回调通知
 * @author MrW
 */
@Slf4j
@RestController
@RequestMapping("api")
public class KftPayController {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private RegionRecordMapper regionRecordMapper;
    @Autowired
    private ProfitConfigMapper profitConfigMapper;
    @Autowired
    private PoundageConfigMapper poundageConfigMapper;
    @Autowired
    private PlatformMapper platformMapper;
    @Autowired
    private KftCoreManager kftCoreManager;
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private KppAppPayConfiguration kppAppPayConfiguration;
    @Autowired
    private KftPayCommConfig kftPayCommConfig;

    /**
     * 消费者通过微信app支付给快付通平台的异步回调通知给商户系统
     */
    @RequestMapping(value = "/open/kft_notify", method = RequestMethod.POST)
    @ResponseBody
    public String kftNotify(NotifyRes notifyRes) {
        Date date = new Date();
        //111
        Map<String,String> map = notifyRes.toMap();
        if (map == null || map.isEmpty()) {
            log.warn("快付通回调解析失败->回调参数为空");
            return "";
        }
        //生成签名
        KftPayConfigStorage kftPayConfigStorage = new KftPayConfigStorage();
        kftPayConfigStorage.setPackPath(kftPayCommConfig.getPackPath());
        kftPayConfigStorage.setSftpPath(kftPayCommConfig.getSftpPath());
        kftPayConfigStorage.setSftpHost(kftPayCommConfig.getSftpHost());
        kftPayConfigStorage.setSftpUsername(kftPayCommConfig.getSftpUsername());
        kftPayConfigStorage.setSftpPassword(kftPayCommConfig.getSftpPassword());
        kftPayConfigStorage.setKeyPrivate(kftPayCommConfig.getKeyPrivate());
        kftPayConfigStorage.setDevGateWay(kftPayCommConfig.getDevGateWay());
        kftPayConfigStorage.setGateWay(kftPayCommConfig.getGateWay());
        kftPayConfigStorage.init();
        KftPayService kftPayService = new KftPayService(kftPayConfigStorage);
        //生成签名字符串
        Map<String,String> signMap = kftPayService.createSign(map);
        String sign = signMap.get( "signatureInfo" );
        //校验签名
        if(sign.equals( notifyRes.getSignatureInfo() )){
            //校验成功
            log.info( "快付通校验签名成功" );
            String orderNum = notifyRes.getOrderNo();
            Order order = orderMapper.selectByOrderNum( notifyRes.getOrderNo() );
            BigDecimal totalPrice = order.getTotalPrice().add(order.getTipPrice());

            if (notifyRes.getStatus() == null || "".equals( notifyRes.getStatus() )) {

            /*如果一段时间内没有收到快付通平台的异步通知,调用查询结果查询交易结果
               建议每隔8秒查询一次，如果商户主动查询到交易终态结果，快付通系统将不再发送异步通知。*/
                log.info( "还没有收到快付通平台的异步通知" );
                return "";
            } else {


                if ("1".equals( notifyRes.getStatus() )) {
                    if (order.getStatus() != 0) {
                        //订单已经回调通知排除已成功通知
                        log.info("快付通支付" + orderNum + "重复通知支付结果！");
                        return "success";
                    }

                    log.info( "快付通支付" + orderNum + "支付成功！" );
                    //消费者信息
                    Member member = memberMapper.selectByPrimaryKey( order.getmId() );
                    //商家店铺信息
                    Store store = storeMapper.selectByPrimaryKey( order.getStoreId() );

                    Message message1 = new Message();
                    message1.setTargetName( "" );
                    message1.setTarget( store.getmId() );
                    message1.setFromName( "系统" );
                    message1.setFrom( 0L );
                    message1.setTitle( "新订单提醒" );
                    message1.setContent( "您有新的订单产生请及时处理，订单编号：" + orderNum );
                    message1.setCreateTime( date );
                    message1.setModifyTime( date );
                    messageMapper.insertSelective( message1 );
                    SendJPushMessage.jPushByMessage( message1 );
                    Order update = new Order();
                    update.setPayType( 4 );
                    update.setId( order.getId() );
                    //对于企业订单消费者确认收货之后才去分成
                    String online = "online";
                    if (order.getOrderType().equals( online )) {
                        //企业订单
                        //更新订单支付状态

                        update.setStatus( 1 );
                        orderMapper.updateByPrimaryKeySelective( update );
                    } else {
                        orderMapper.updateByPrimaryKeySelective( update );
                        //直接消费订单

                        //消费者账户信息
                        Account account = accountMapper.selectByMid( order.getmId() );

                        CompanyReport companyReport = new CompanyReport();
                        companyReport.setReserve1( "快付通消费,订单编号" + orderNum );
                        companyReport.setReserve2( "6" );
                        //商家账户信息
                        Account merchantAccount = accountMapper.selectByMid( store.getmId() );
                        //商户信息
                        Member merchant = memberMapper.selectByPrimaryKey( store.getmId() );

                        Member memberUp = null;
                        if (member.getInvitedCode() != null) {
                            //用户上线
                            memberUp = memberMapper.selectMyUp( member.getInvitedCode() );
                        }
                        Member merchantUp = null;
                        if (merchant.getInvitedCode() != null) {
                            //商户上线
                            merchantUp = memberMapper.selectMyUp( merchant.getInvitedCode() );
                        }
                        //店铺的省市区三级代理商获取
                        RegionRecord province = regionRecordMapper.selectProvince( store.getProvince() );
                        RegionRecord city = regionRecordMapper.selectProvinceAndCity( store.getProvince(), store.getCity() );
                        RegionRecord region = regionRecordMapper.selectProvinceAndCityAndRegion( store.getProvince(), store.getCity(), store.getRegion() );

                        //总的奖励分配
                        BigDecimal totalBonus = new BigDecimal( "0" );

                        //利润分配配置
                        ProfitConfig config = profitConfigMapper.selectByPrimaryKey( 1L );
                        //msk卖出配置
                        PoundageConfig poundageConfig = poundageConfigMapper.selectByPrimaryKey( 1L );
                        //平台账户信息
                        Platform platform = platformMapper.selectByPrimaryKey( 1L );
                        synchronized (this) {

                            //核心处理方法
                            kftCoreManager.coreOperation( order, totalPrice, totalBonus, order.getTransferPrice(), config, poundageConfig, platform, member, memberUp, account, merchant, merchantUp
                                    , province, city, region, date, store, companyReport );

                        }
                    }
                    // 推送消息
                    Message message = new Message();
                    message.setModifyTime( date );
                    message.setCreateTime( date );
                    message.setContent( "尊敬的用户您使用快付通支付订单：" + orderNum + "，" + totalPrice + " 元。成功支付！" );
                    message.setTitle( "支付结果" );
                    message.setFrom( 0L );
                    message.setFromName( "系统" );
                    message.setTarget( member.getId() );
                    message.setTargetName( member.getNickName() );
                    messageMapper.insertSelective( message );
                    SendJPushMessage.jPushByMessage( message );
                } else {
                    log.info( "快付通支付" + orderNum + "支付失败！回退订单锁定库存，删除订单，及订单明细！" );
                    //支付不成功回退订单锁定库存，删除订单，及订单明细
                    List<OrderGoods> orderGoods = orderGoodsMapper.selectByOrderId( order.getId() );
                    for (OrderGoods o : orderGoods) {
                        //回退库存
                        goodsMapper.numAdd( o.getNum(), o.getId() );
                    }
                    orderMapper.deleteByPrimaryKeyLogic(order.getOrderNum());
                    Message message = new Message();
                    message.setModifyTime(date);
                    message.setCreateTime(date);
                    message.setContent("尊敬的用户您使用快付通支付订单：" + orderNum + "，" + totalPrice + " 元。支付失败！");
                    message.setTitle("支付结果");
                    message.setFrom(0L);
                    message.setFromName("系统");
                    message.setTarget(order.getmId());
                    message.setTargetName("");
                    messageMapper.insertSelective(message);
                    SendJPushMessage.jPushByMessage(message);
                    return "";

                }
                return "success";
        }




        }else{
            //校验失败
            log.info( "快付通校验签名失败");
            return "";
        }

    }
}




